package org.examcity.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

/**
 * Entity that represents an objective that can be evaluated by exams.
 * <p>
 * Every objective is contained in a {@link Subject}.
 * @author Antonio Gomes
 */
@Entity
@Table(name = "EC_OBJECTIVE")
public class Objective {

	// ATTRIBUTES ----------------------------------------------------------------------------------

	@Id
	@Column(name = "OBJECTIVE_ID")
	@SequenceGenerator(name = "SEQ_EC_OBJECTIVE")
	private Long id;

	@Column(nullable = false, length = 50)
	private String name;

	@Column(length = 250)
	private String description;

	@ManyToOne
	@JoinColumn(name = "SUBJECT_ID", referencedColumnName = "SUBJECT_ID", nullable = false)
	private Subject subject;

	// ACCESSORS -----------------------------------------------------------------------------------

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Long getId() {
		return id;
	}

	public Subject getSubject() {
		return subject;
	}

	/**
	 * Sets the subject of this objective.
	 * <p>
	 * This method handles the bi-directional link automatically.
	 * @param subject
	 */
	public void setSubject(Subject subject) {
		if (this.subject != null) {
			this.subject._removeObjective(this);
			this.subject = null;
		}
		if (subject != null) {
			this.subject = subject;
			this.subject._addObjective(this);
		}
	}

	// OTHER METHODS -------------------------------------------------------------------------------

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(name).append(subject).toHashCode();
	}

	@Override
	public boolean equals(Object _o) {
		if (_o instanceof Objective) {
			Objective o = (Objective) _o;
			return new EqualsBuilder()
					.append(name, o.getName())
					.append(subject, o.getSubject())
					.isEquals();
		}
		return false;
	}

}
